package com.mars.common.util;

import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;


/**
 * RSAUtils
 *
 * @author 程序员Mars
 * @version 1.0
 * @date 2023-12-08 15:11:46
 */
public class RSAUtils {


    private static final String RSA_ALGORITHM = "RSA";

    public static String PUBLIC_KEY_STRING = "";

    public static String PRIVATE_KEY_STRING = "";

    public static PublicKey PUBLIC_KEY = null;

    public static PrivateKey PRIVATE_KEY = null;

    static {
        // 生成RSA密钥对
        KeyPair keyPair;
        try {
            keyPair = RSAUtils.generateKeyPair(512);
            PUBLIC_KEY = keyPair.getPublic();
            PRIVATE_KEY = keyPair.getPrivate();
            // 将公钥和私钥转换为字符串
            PUBLIC_KEY_STRING = Base64.getEncoder().encodeToString(PUBLIC_KEY.getEncoded());
            PRIVATE_KEY_STRING = Base64.getEncoder().encodeToString(PRIVATE_KEY.getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static KeyPair generateKeyPair(int keySize) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }

    public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedData);
    }

    /**
     * 公钥加密
     *
     * @param data data
     * @return String
     */
    public static String encode(String data) throws Exception {
        byte[] originalBytes = data.getBytes();
        // 使用公钥加密
        byte[] encryptedBytes = RSAUtils.encrypt(originalBytes, PUBLIC_KEY);
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 私钥解密
     *
     * @param encodeData encodeData
     * @return String
     */
    public static String decode(String encodeData) throws Exception {
        // 使用私钥解密
        byte[] decryptedBytes = RSAUtils.decrypt(Base64.getDecoder().decode(encodeData), PRIVATE_KEY);
        return new String(decryptedBytes);
    }

    /**
     * 获取公钥
     *
     * @return String
     */
    public static String getPublicKeyString() {
        return PUBLIC_KEY_STRING;
    }


    public static void main(String[] args) throws Exception {


    }

}
